package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego/logs"
	services "tinyrdm/backend/services"
	"tinyrdm/backend/types"
)

var connLog = logs.GetLogger("Cli")

type ConnectionController struct {
	BaseController
}

type ConnReqData struct {
	Method      string                  `json:"method"`
	Server      string                  `json:"server"`
	Config      *types.ConnectionConfig `json:"config"`
	Group       string                  `json:"group"`
	NewGroup    string                  `json:"newGroup"`
	Name        string                  `json:"name"`
	IncludeConn bool                    `json:"includeConn"`
	Url         string                  `json:"url"`
	Db          int                     `json:"db"`
	Interval    int                     `json:"interval"`

	Connections *types.Connections `json:"connections"`
	Params      []map[string]any   `json:"params"`
}

var conn = services.Connection()

func (c *ConnectionController) Handler() {
	conn.Start(c.context())
	var req ConnReqData
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		logs.Error(err, string(c.Ctx.Input.RequestBody))
		c.ErrorJson(err)
		return
	}
	var resp any
	switch req.Method {
	case "Start":
		break
	case "TestConnection":
		resp = conn.TestConnection(*req.Config)
		break
	case "SaveConnection":
		resp = conn.SaveConnection(req.Name, *req.Config)
		break
	case "DeleteConnection":
		resp = conn.DeleteConnection(req.Name)
		break
	case "CreateGroup":
		resp = conn.CreateGroup(req.Group)
		break
	case "DeleteGroup":
		resp = conn.DeleteGroup(req.Group, req.IncludeConn)
		break
	case "ExportConnections":
		//涉及到文件保存这种，还是会有问题
		resp = conn.ExportConnections()
		break
	case "GetConnection":
		resp = conn.GetConnection(req.Name)
		break
	case "ImportConnections":
		resp = conn.ImportConnections()
		break
	case "ListConnection":
		resp = conn.ListConnection()
		break
	case "ListSentinelMasters":
		resp = conn.ListSentinelMasters(*req.Config)
		break
	case "ParseConnectURL":
		resp = conn.ParseConnectURL(req.Url)
		break
	case "RenameGroup":
		resp = conn.RenameGroup(req.Group, req.NewGroup)
		break
	case "SaveLastDB":
		resp = conn.SaveLastDB(req.Name, req.Db)
		break
	case "SaveRefreshInterval":
		resp = conn.SaveRefreshInterval(req.Name, req.Interval)
		break
	case "SaveSortedConnection":
		resp = conn.SaveSortedConnection(*req.Connections)
		break

	default:
		resp = types.JSResp{
			Success: false,
			Msg:     "未找到该方法",
			Data:    nil,
		}
		connLog.Printf("not found: %s", req.Method)
	}
	if resp == nil {
		resp = types.JSResp{
			Success: true,
			Msg:     "Successful",
			Data:    nil,
		}
	}
	c.postJson(resp)
}
